package com.ivo.activiti.bpmn;

import com.ivo.activiti.bpmn.record.Execution;
import com.ivo.activiti.bpmn.record.RecordService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * activiti监听器
 * @author wj
 * @version 1.0
 */
@Service
public class IvoActivitiEventListener implements ActivitiEventListener {

    @Resource
    private RecordService recordService;

    @Override
    public void onEvent(ActivitiEvent event) {
        switch (event.getType()) {
            //流程开始
            case PROCESS_STARTED:
                test(event);
                break;
            //流程结束
            case PROCESS_COMPLETED:
                test(event);
                break;
            //任务开始
            case TASK_CREATED:
                test(event);
                createTASK(event);
                break;
            //任务分配
            case TASK_ASSIGNED:
                test(event);
                break;
            //任务完成
            case TASK_COMPLETED:
                test(event);
                completeTask(event);
                break;
            //流程结束
            case PROCESS_CANCELLED:
                test(event);
            default:
                test(event);
        }
    }

    public void test(ActivitiEvent event) {
        System.out.println("IvoActivitiEventListener:"+event.getType());
        if(!StringUtils.startsWithAny(event.getType().name(), "TASK")) return;
        if(event instanceof ActivitiEntityEvent) {
            ActivitiEntityEvent e = (ActivitiEntityEvent) event;
            System.out.println(e.getEntity());
        }
    }

    void createTASK(ActivitiEvent event) {
        ActivitiEntityEvent e = (ActivitiEntityEvent) event;
        Task task = (Task) e.getEntity();
        task.getAssignee();
        recordService.createExecution(task.getId(), task.getBusinessKey(), task.getTaskDefinitionKey());
    }

    void completeTask(ActivitiEvent event) {
        ActivitiEntityEvent e = (ActivitiEntityEvent) event;
        Task task = (Task) e.getEntity();
        recordService.completeTask(task.getId());
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}


